package com.dome.reflect;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

//反射测试类
public class RcflectTest {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException, IllegalAccessException, InstantiationException, InvocationTargetException, IOException {
        //先加载prop文件,获取里面的信息
        InputStream systemResourceAsStream = ClassLoader.getSystemResourceAsStream("prop.properties");
        Properties properties=new Properties();
        properties.load(systemResourceAsStream);
        //用Class.forName方法获取properties文件中的全类名和方法名
        String className = properties.getProperty("className");
        Class aClass = Class.forName(className);
        //调用aClass中的方法获取构造方法对象
        //获取所有构造方法对象
        Constructor declaredConstructor = aClass.getDeclaredConstructor();
        System.out.println(declaredConstructor);
        //所有构造方法数组,并遍历
        Constructor[] declaredConstructors = aClass.getDeclaredConstructors();
        for (Constructor constructor : declaredConstructors) {
            System.out.println(constructor);
        }

        System.out.println("=================================");

        //获取成员变量对象,并赋值
        Field name = aClass.getDeclaredField("name");
        Field age = aClass.getDeclaredField("age");
        //由于成员变量是私有的,需要取消访问检查
        name.setAccessible(true);
        age.setAccessible(true);
        //创建类的对象,将赋值的对象封装到对象
        Object o = aClass.newInstance();
        name.set(o,"luxian");
        age.set(o,17);
        System.out.println(o);

        System.out.println("=================================");

        //获取成员方法对象
        Method method1 = aClass.getDeclaredMethod("work");
        method1.invoke(o);
        Method method2 = aClass.getDeclaredMethod("getMothod");
        method2.setAccessible(true);
        Object result = method2.invoke(o);
        System.out.println(result);
    }
}
